<script setup name="Import" lang="ts">
import {
  BOX_TYPE_ENUM,
  COLUMN_TYPE_MAP,
  JAVA_TYPE_ENUM,
  JAVA_TYPE_TO_BOX_TYPE
} from "@/views/tool/generate/const";

const { proxy } = getCurrentInstance();

const props = defineProps({
  id: {
    default: null,
  },
  title: {
    type: String,
    default: false,
  }
})

const emit = defineEmits(['closeDialog']);

//弹窗开关
const open = ref(false);

//表单数据
const form = ref({});

//表单校验
const rules = ref({
  apiData: [
    { required: true, message: "请输入数据", trigger: "blur" },
  ],
})

function getData() {
  form.value = {
    apiData: '',
    tableList: [],
  }
  open.value = true;
}

/** 关闭弹窗 */
function closeDialog(refresh, data) {
  open.value = false;
  let dData = {
    refresh,
    data
  }
  emit("closeDialog", dData)
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["impForm"].validate((valid: boolean) => {
    if (valid) {
      let dataArr = form.value.apiData.split("\n");
      let columnArr: any = [];
      dataArr.forEach((item, index) => {
        if (index % 2 == 0) {
          let columns = item.split('\t');
          if (columns && columns.length > 1) {
            if (dataArr[index + 1].includes(JAVA_TYPE_ENUM.integer)) {
              dataArr[index + 1] = JAVA_TYPE_ENUM.integer
            }
            let generate = {
              colNo: null,
              sId: new Date().getTime() + "" + index,
              columnName: columns[0],
              columnNotes: columns[1],
              columnType: COLUMN_TYPE_MAP[dataArr[index + 1]] || COLUMN_TYPE_MAP[JAVA_TYPE_ENUM.string],
              boxType: JAVA_TYPE_TO_BOX_TYPE[dataArr[index + 1]] || BOX_TYPE_ENUM.input,
              dictType: '',
              required: columns[3],
            }
            columnArr.push(generate);
          }
        }
      })
      form.value.tableList = columnArr;
      closeDialog(true, columnArr);
    }
  })
}

watch(open, (val) => {
  if (!val) {
    closeDialog(false);
  }
})
getData();
</script>

<template>
  <el-dialog :title="title" v-model="open" width="900px" append-to-body :close-on-click-modal="false">
    <el-form ref="impForm" :model="form" :rules="rules" :inline="true" label-width="80px">
      <el-form-item label="接口数据" class="item-describe" prop="apiData">
        <el-input type="textarea" v-model="form.apiData" placeholder="请输入描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" v-debounce="submitForm">确 定</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-textarea) {
  min-width: 750px;

  textarea {
    min-height: 260px !important;
  }

}
</style>